package com.yuexunit.mobilenurse.module.Chemical.presenter.impl;

import com.alibaba.fastjson.JSON;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.Chemical.bean.ChemicalDetailBean;
import com.yuexunit.mobilenurse.module.Chemical.bean.YXChemicalBean;
import com.yuexunit.mobilenurse.module.Chemical.model.IChemicalModel;
import com.yuexunit.mobilenurse.module.Chemical.model.impl.ChemicalModel;
import com.yuexunit.mobilenurse.module.Chemical.presenter.IChemicalPresenter;
import com.yuexunit.mobilenurse.module.Chemical.ui.view.IChemicalView;
import com.yuexunit.mobilenurse.util.RxUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.ui.ViewInject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by work-jx on 2016/6/29.
 */
public class ChemicalPresenter implements IChemicalPresenter{
    //记录Log
    private final Logger log = LoggerFactory.getLogger(ChemicalModel.class);

    private IChemicalView view;
    private IChemicalModel model;
    private CompositeSubscription compositeSubscription = new CompositeSubscription();

    ArrayList<ChemicalDetailBean> chemicalDetailBeans  = new ArrayList<ChemicalDetailBean>();

    public ChemicalPresenter(IChemicalView view, IChemicalModel model) {
        this.view = view;
        this.model = model;
    }

    @Override
    public void showChemicalDate(String barcode) {
        compositeSubscription.add(
                model.getChemicalDate(barcode)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<String>() {

                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {
                                log.error("Exception", e);
                                ViewInject.toast("暂无化药数据");
                            }

                            @Override
                            public void onNext(String result) {

                                YXChemicalBean Total = JSON.parseObject(result, YXChemicalBean.class);
                                YXChemicalBean ChemicalData = Total.getBody();

                                if ("0".equals(ChemicalData.getHead().getRet_code())) {
                                    List<ChemicalDetailBean> chemicalDetailBeanlist;
                                    String chemical = ChemicalData.getResponse().getInfusion();
                                    String chemical_first = chemical.substring(0, 1);
                                    if (!chemical_first.equals("[")) {
                                        chemical = "[" + chemical + "]";
                                        chemicalDetailBeanlist = JSON.parseArray(chemical, ChemicalDetailBean.class);
                                    } else {
                                        chemicalDetailBeanlist = JSON.parseArray(chemical, ChemicalDetailBean.class);
                                    }

                                    for(int i = 0;i<chemicalDetailBeanlist.size();i++)
                                    {
                                        chemicalDetailBeans.add(chemicalDetailBeanlist.get(i));
                                    }

                                    view.showChemicalDate(chemicalDetailBeans);
                                }
                                else {
                                    ViewInject.toast("暂无化药数据");
                                }

                            }
                        }
                        )
        );
    }

    @Override
    public void execChemicalDate(String barcode, String nurseid) {
        compositeSubscription.add(
                model.execChemicalDate(barcode, nurseid)
                        .subscribeOn(Schedulers.io())
                        .doOnSubscribe(new Action0() {
                            @Override
                            public void call() {
                                view.loadingDialogStatus(AppConfig.SHOW_DIALOG);
                            }
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<String>() {

                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {
                                log.error("Exception", e);
                                view.loadingDialogStatus(AppConfig.DISMISS_DIALOG);
                                view.isExecSuccess(false);
                            }

                            @Override
                            public void onNext(String s) {
                                JSONObject all, body, response,head;
                                String ret_code = "-1";
                                try {
                                    all = new JSONObject(s.toString());
                                    body = all.getJSONObject("body");
                                    response=body.getJSONObject("response");
                                    head = response.getJSONObject("head");
                                    ret_code = head.getString("ret_code");
                                } catch (JSONException e) {
                                }

                                if ("0".equals(ret_code)) {
                                    view.loadingDialogStatus(AppConfig.DISMISS_DIALOG);
                                    view.isExecSuccess(true);
                                } else {
                                    view.loadingDialogStatus(AppConfig.DISMISS_DIALOG);
                                    view.isExecSuccess(false);
                                }
                            }
                        })
        );
    }

    public CompositeSubscription getCompositeSubscription() {
        return RxUtils.getNewCompositeSubIfUnsubscribed(compositeSubscription);
    }

    public void UnSubObservers() {
        if (compositeSubscription != null && !compositeSubscription.isUnsubscribed()) {
            compositeSubscription.unsubscribe();
        }

    }
}
